#ifndef __movies_xml_hpp__
#define __movies_xml_hpp__

#include <iostream>
#include <fstream>
#include <string>
#include <map>

#include "Movie.hpp"
#include "funcs.hpp"

using namespace std;

#define MOVIES_LIST "lists/movies.list"
#define GENRES_LIST "lists/genres.list"
#define TITLES_LIST "lists/aka-titles.list"

#define MOVIES_XML "xml/movies.xml"

bool parse_movies(map<string,Movie>& movies)
{
  string line;
  
  ifstream fmovies;
  fmovies.open(MOVIES_LIST);
  if ( !fmovies.is_open() )
    return false;
  
  while( getline(fmovies, line) && line != "" ) {
    Movie mov;
    mov.parse(line);
    movies.insert( pair<string,Movie>(mov.title, mov) );
  }

  fmovies.close();

  return true;
}

bool parse_genres(map<string,Movie>& movies)
{
  string line;

  ifstream fgenres;
  fgenres.open(GENRES_LIST);
  if ( !fgenres.is_open() )
    return false;

  while( getline(fgenres, line) && line != "" ) {
    size_t fst_tab = line.find('\t');
    size_t lst_tab = line.rfind('\t');

    string mov_tit = trim(line.substr(0, fst_tab)); 
    map<string,Movie>::iterator mov_it = movies.find( mov_tit );
    if ( mov_it == movies.end() ){
      cerr << "MOVIE NOT FOUND: " << mov_tit << endl;
    } else {
      mov_it->second.add_genre( trim(line.substr(lst_tab+1)) );
    }
  }

  fgenres.close();
  
  return true;
}

bool parse_aka_titles(map<string,Movie>& movies)
{
  string line;

  ifstream ftitles;
  ftitles.open(TITLES_LIST);
  if ( !ftitles.is_open() ) {
    cerr << "ERROR OPENING FILE " << TITLES_LIST << endl;
    return false;
  }

  bool ignore = false;
  map<string,Movie>::iterator mov_it = movies.end();
  while( getline(ftitles, line) ) {
    if ( line == "" ) {
      ignore = false;
      mov_it = movies.end();
      continue;
    }

    if ( ignore ) continue;

    if ( mov_it == movies.end() ) {
      mov_it = movies.find( line );
      if ( mov_it == movies.end() ) {
	cerr << "MOVIE NOT FOUND: " << line << " (IGNORING)" << endl;
	ignore = true;
      }
    } else {
      size_t beg = line.find("(aka ") + 5;
      size_t end = line.find("\t", beg);
      if ( end == string::npos ) end = line.length();
      --end;
      
      string aka = trim(line.substr(beg, end-beg));
      if ( aka != mov_it->second.title )
	mov_it->second.add_aka(aka);
    }
  }

  ftitles.close();

  return true;
}

bool gen_movies_xml(map<string,Movie>& movies)
{
  ofstream moviesxml;
  moviesxml.open( MOVIES_XML );

  if ( !moviesxml.is_open() )
    return false;

  moviesxml << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << endl;
  moviesxml << "<movies xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \
xsi:noNamespaceSchemaLocation=\"movies.xsd\">" << endl;
  map<string,Movie>::const_iterator it;
  for(it = movies.begin(); it != movies.end(); ++it)
    moviesxml << it->second << endl;
  moviesxml << "</movies>" << endl;

  moviesxml.close();

  return true;
}

#endif
